package org.example.base.common.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.example.base.common.dao.UserDao;
import org.example.base.common.entity.UserEntity;
import org.example.base.common.model.TUserRoleModel;
import org.example.base.common.model.UserModel;
import org.example.base.common.repository.UserRepository;
import org.example.base.common.service.TUserRoleService;
import org.example.base.common.service.UserService;
import org.example.core.constanct.CommonUtils;
import org.example.core.exception.ErrorException;
import org.example.core.mysql.Where;
import org.example.core.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户Service实现类
 */
@Primary
@Service
public class UserServiceImpl extends BaseServiceImpl<String, UserModel, UserEntity, UserRepository, UserDao> implements UserService {


    @Autowired
    private UserDao userDao;

    @Autowired
    private TUserRoleService tUserRoleService;

    @Override
    public JSONObject getUserInfo() {
        JSONObject result = new JSONObject();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object userId = ((User) authentication.getPrincipal()).getUsername();
        UserModel userModel = getById((String) userId);
        //用户有多个角色，菜单可能一致，需要进行去重
        List<Map<String, Object>> menus = userDao.getMenusByUserId(userId)
                .stream()
                .distinct()
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(menus)) {
            throw new ErrorException("该用户未配置资源菜单！");
        }
        List<Map<String, Object>> topMenuList = menus.stream()
                .filter(menuMap -> ObjectUtils.isEmpty(menuMap.get("parentId")))
                .sorted((o1, o2) -> {
                    if (ObjectUtils.isEmpty(o1)) {
                        return 1;
                    }
                    if (ObjectUtils.isEmpty(o2)) {
                        return 1;
                    }
                    int ord1 = Integer.parseInt(String.valueOf(o1.get("ord")));
                    int ord2 = Integer.parseInt(String.valueOf(o2.get("ord")));
                    return ord1 - ord2;
                }).collect(Collectors.toList());
        result.put("menu", convertMenusDataStructure(menus, topMenuList));
        result.put("id", userId);
        result.put("name",userModel.getName());
        result.put("user",userModel);
        return result;
    }

    private JSONArray convertMenusDataStructure(List<Map<String, Object>> menus, List<Map<String, Object>> topMenuList) {
        JSONArray result = new JSONArray();
        if (CollectionUtils.isEmpty(topMenuList)) {
            return result;
        }
        for (Map<String, Object> topMenu : topMenuList) {
            JSONObject menuJsonObject = new JSONObject(topMenu);
            String id = String.valueOf(topMenu.get("id"));
            List<Map<String, Object>> childrenList = menus.stream()
                    .filter(menuMap -> id.equals(menuMap.get("parentId")))
                    .sorted((o1, o2) -> {
                        if (ObjectUtils.isEmpty(o1)) {
                            return 1;
                        }
                        if (ObjectUtils.isEmpty(o2)) {
                            return 1;
                        }
                        int ord1 = Integer.parseInt(String.valueOf(o1.get("ord")));
                        int ord2 = Integer.parseInt(String.valueOf(o2.get("ord")));
                        return ord1 - ord2;
                    })
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(childrenList)) {
                menuJsonObject.put("children", childrenList);
                convertMenusDataStructure(menus, childrenList);
            }
            result.add(menuJsonObject);
        }
        return result;
    }

    @Override
    public void addRoles(Map<String, Object> params) {
        Object roleIds = params.get("roleIds");
        Object userId = params.get("userId");
        //删除之前该用户的
        List<TUserRoleModel> userModelList = tUserRoleService.search(Where.build().field("user_id").equal(userId));
        userModelList.stream().map(TUserRoleModel::getId).forEach(userRoleId -> {
            tUserRoleService.delete(userRoleId);
        });
        List<String> roleIdList = (List<String>) roleIds;
        userDao.addRoles(roleIdList, userId);
    }

    @Override
    public JSONObject getDetail(String id) {
        UserModel userModel = getById(id);
        JSONObject resultJsonObject = JSONObject.parseObject(JSONObject.toJSONString(userModel));
        resultJsonObject.put("roleIdList", tUserRoleService
                .search(Where.build().field("user_id")
                        .equal(userModel.getId()))
                .stream().map(TUserRoleModel::getRoleId)
                .collect(Collectors.toList()));
        return resultJsonObject;
    }

    @Override
    public void register(Map<String, Object> params) {
        Object account = params.get("account");
        Object password = params.get("password");
        Object name = params.get("name");
        Object location = params.get("location");
        Object sex = params.get("sex");
        Object telephone = params.get("telephone");
        Object img = params.get("img");
        UserModel currentUserModel = searchOne(Where.build().field("account").equal(account).and().field("del_flag").equal(0));
        if (!ObjectUtils.isEmpty(currentUserModel)){
            throw new ErrorException("账号已存在！");
        }
        UserModel userModel = new UserModel();
        String id = CommonUtils.getUUID().replaceAll("-","");
        userModel.setId(id);
        userModel.setAccount(String.valueOf(account));
        userModel.setPassword(String.valueOf(password));
        userModel.setName((String) name);
        userModel.setLocation((String) location);
        userModel.setSex((String) sex);
        userModel.setTelephone((String) telephone);
        userModel.setImg((String) img);
        userModel.setName("用户"+System.currentTimeMillis());
        add(userModel);
        //新增角色
        TUserRoleModel tUserRoleModel = new TUserRoleModel();
        tUserRoleModel.setRoleId("base-user");
        tUserRoleModel.setUserId(id);
        tUserRoleService.add(tUserRoleModel);
    }

    @Override
    public void modifyPassword(Map<String, Object> params) {
        Object password = params.get("password");
        Object id = params.get("userId");
        UserModel userModel = getById((String) id);
        userModel.setPassword((String) password);
        update(userModel);
    }

}
